<template>
    <div class="login">
        <div class="nav">
            <div class="nav-content">
                <router-link to="/home">
                    <img src="../../assets/1.png" alt />
                </router-link>
                <span>登录账号</span>
            </div>
        </div>
        <div class="form-1">
            <h1>登录</h1>
            <div>
                <el-form :model="loginForm" :rules="loginRules" ref="loginForm">
                    <el-form-item prop="username">
                        <el-input
                            ref="username"
                            v-model="loginForm.username"
                            placeholder="请输入手机号"
                            name="username"
                            type="text"
                            tabindex="1"
                        ></el-input>
                    </el-form-item>
                    <el-tooltip v-model="capsTooltip" content="大写锁定打开" placement="right" manual>
                        <el-form-item prop="password">
                            <el-input
                                :key="passwordType"
                                ref="password"
                                v-model="loginForm.password"
                                :type="passwordType"
                                placeholder="请输入密码（6-16位）"
                                name="password"
                                tabindex="2"
                                autocomplete="on"
                                @keyup.native="checkCapslock"
                                @blur="capsTooltip = false"
                                @keyup.enter.native="handleLogin"
                            ></el-input>
                            <span class="show-pwd" @click="showPwd">
                                <i
                                    :class="[passwordType === 'password' ? 'iconbukejian' : 'iconkejian','iconfont'] "
                                />
                            </span>
                        </el-form-item>
                    </el-tooltip>
                    <el-button
                        :loading="loading"
                        type="primary"
                        style="width:100%;margin-bottom:30px;"
                        @click.native.prevent="handleLogin"
                    >登录</el-button>
                </el-form>
                <div class="form-fot">
                    <router-link to="/retrieve">忘记密码</router-link>
                    <p>
                        <strong>没有账号?</strong>
                        <router-link to="/register">去注册</router-link>
                    </p>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
import { validPhone, validEmpty } from '@/utils/validate'
export default {
    data() {
        const validateUsername = (rule, value, callback) => {
            if (validEmpty(value)) {
                callback(new Error('手机号不能为空'))
            }
            else if (!validPhone(value)) {
                callback(new Error('请输入正确的手机号'))
            } else {
                callback()
            }
        }
        const validatePassword = (rule, value, callback) => {
            if (value.length < 1) {
                callback(new Error('密码不能小于6位'))
            } else {
                callback()
            }
        }
        return {
            loginForm: {
                username: '',
                password: ''
            },
            loginRules: {
                username: [{ required: true, trigger: 'blur', validator: validateUsername }],
                password: [{ required: true, trigger: 'blur', validator: validatePassword }]
            },
            passwordType: 'password',
            capsTooltip: false,
            loading: false,
            redirect: undefined,
            otherQuery: {}
        }
    },
    mounted() {
        if (this.loginForm.username === '') {
            this.$refs.username.focus()
        } else if (this.loginForm.password === '') {
            this.$refs.password.focus()
        }
        // this.getInfo()
    },
    methods: {
        async getInfo() {
            // const user = jwt_decode(getToken())
            const res = await this.$store.dispatch('user/getInfoList')
            console.log(res)
        },
        checkCapslock(e) {
            const { key } = e
            this.capsTooltip = key && key.length === 1 && (key >= 'A' && key <= 'Z')
        },
        showPwd() {
            if (this.passwordType === 'password') {
                this.passwordType = ''
            } else {
                this.passwordType = 'password'
            }
            this.$nextTick(() => {
                this.$refs.password.focus()
            })
        },
        handleLogin() {
            this.$refs.loginForm.validate(valid => {
                if (valid) {
                    this.loading = true
                    this.$store.dispatch('user/login', this.loginForm)
                        .then((res) => {
                            this.$router.push({ path: this.redirect || '/', query: this.otherQuery || '' })
                            this.loading = false
                            localStorage.zgzxwzhangh = JSON.stringify(this.loginForm)
                        })
                        .catch(() => {
                            this.loading = false
                        })
                } else {
                    console.log('error submit!!')
                    return false
                }
            })
        },
        getOtherQuery(query) {
            return Object.keys(query).reduce((acc, cur) => {
                if (cur !== 'redirect') {
                    acc[cur] = query[cur]
                }
                return acc
            }, {})
        }
    },
    watch: {
        $route: {
            handler: function (route) {
                const query = route.query
                if (query) {
                    this.redirect = query.redirect
                    if (this.getOtherQuery(query).query) {
                        this.otherQuery = JSON.parse(this.getOtherQuery(query).query);
                    }
                }
            },
            immediate: true
        }
    },
}
</script>

<style scoped>
@import "./login.css";
</style>